/**
 * 
 */
package net.socket;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.Scanner;

/**
 * @author Niki
 * @version 创建时间：2017年3月2日 下午11:07:30 类说明
 */
public class Client {
    public static void main(String[] args) {
        dataStreamSocket();
    }

    private static void streamSocket() {
        try {
            Socket client = new Socket("127.0.0.1", 9000);
            OutputStream os = client.getOutputStream();
            InputStream is = new BufferedInputStream(client.getInputStream());
            int len;
            StringBuilder result = new StringBuilder();
            while ((len = is.read()) > 1) {
                result.append((char) len);
            }
            System.out.println(result.toString());
            String msg = "hello server ！";
            byte[] msgData = msg.getBytes(Charset.forName("UTF-8"));
            os.write(msgData, 0, msgData.length);
            os.flush();
            client.shutdownOutput();
            is.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void dataStreamSocket() {
        try {
            Socket client = new Socket("127.0.0.1", 9000);
            DataOutputStream out = new DataOutputStream(client.getOutputStream());
            DataInputStream in = new DataInputStream(client.getInputStream());
            Scanner scanner = new Scanner(System.in);
            while (true) {
                // 先发送信息到服务端，再从服务端获得信息
                String input = scanner.nextLine();
                // out.writeChars(input);
                out.writeUTF(input);
                // out.flush();
                // out.close();
                String serverMsg = in.readUTF();
                System.out.println("server give me msg is:" + serverMsg);
                if (input.equals("quit"))
                    break;
            }
            in.close();
            out.close();
            client.close();
            scanner.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
